import { deepCopy } from "./copy"

// default
const BOOL_DEFAULT = false
// data struct
enum DATA_TYPE {
    int = 'int',
    uint = 'uint',
    float = 'float',
    string = 'string',
    bool = 'bool',
    choice = 'choice',
    time = 'time',
    file = 'file',
    json = 'json',
    signal = 'signal'
}

interface PropDataType {
    Type: DATA_TYPE;
    Required: boolean;
    Default: unknown;
    Meta: unknown;
    Translation?: string; // 中文或者其他语言的翻译
    Help?: string; // 帮助

}
interface FieldType extends PropDataType {
    Value: unknown | unknown[][];
}

// widgets
enum FORM_WIDGETS {
    INPUT = "input",
    CHOICE_LIST = "choice_list",
    DATE = "date",
    DATETIME = "datetime",
    FILE = "file",
    JSON = "json",
    BOOL = "bool",
}

const DATA_TYPE_TO_INPUT_WIDGETS = {
    int: FORM_WIDGETS.INPUT,
    uint: FORM_WIDGETS.INPUT,
    float: FORM_WIDGETS.INPUT,
    string: FORM_WIDGETS.INPUT,
    choice: FORM_WIDGETS.CHOICE_LIST,
    time: FORM_WIDGETS.DATETIME,
    file: FORM_WIDGETS.FILE,
    json: FORM_WIDGETS.JSON,
    bool: FORM_WIDGETS.BOOL,
    signal: FORM_WIDGETS.INPUT
}
// PropDataType -> FieldType (Default -> Value)
function TransformDataToFields(data: Record<string, PropDataType>): Record<string, FieldType> {
    const newData: Record<string, FieldType> = {}
    for (const key in data) {
        const field: any = deepCopy(data[key])
        // if ("Default" in field) {
        //     field.Value = field.Default
        // } else if (field.Type === DATA_TYPE.bool) {
        //     field.Value = BOOL_DEFAULT
        // } else {
        //     field.Value = null
        // }
        // delete field.Default
        field.Errors = []
        newData[key] = field
    }
    // return BoolChoicesAdd(newData)
    return newData
}
// choice
function BoolChoicesAdd(fields: Record<string, FieldType>): Record<string, FieldType> {
    const fields_ = fields
    for (const key in fields) {
        const field = fields[key]
        if (field != undefined && field.Type === DATA_TYPE.bool) {
            field.Meta = [
                { "value": true, "visual": "是" },
                { "value": false, "visual": "否" },
            ]
            fields_[key] = field
        }
    }
    return fields_
}
// [["a", 1], ["b", 2]] => {a:1, b:2}
function pairsToObject(pairs: Array<Array<unknown>>): Record<string, unknown> {
    const ans: Record<string, unknown> = {}
    for (const i in pairs) {
        const key = pairs[i][0]
        if (typeof key !== "string") { continue }
        ans[key] = pairs[i][1]
    }
    return ans
}
// Date => timestamp
function dateToTimestamp(theDate: Date): number {
    return theDate.getTime()
}


export {
    DATA_TYPE_TO_INPUT_WIDGETS, DATA_TYPE,
    FORM_WIDGETS, FieldType, PropDataType,
    TransformDataToFields, pairsToObject,
    dateToTimestamp
}